package service

import (
	"gitee.com/CrazyMage/blog-service/pkg/ai"
	"github.com/cloudwego/eino/schema"
	"time"
)

const (
	Chat_Context_Length = 50
)

type BlockingChatRequest struct {
	Role           string `form:"role" binding:"required"`
	Prompt         string `form:"prompt" binding:"required"`
	ConversationId string `form:"conversationId" binding:"required"`
}

type StreamingChatRequest struct {
	Role           string `form:"role" binding:"required"`
	Prompt         string `form:"prompt" binding:"required"`
	ConversationId string `form:"conversationId" binding:"required"`
}

func (svc *Service) BlockingChat(param *BlockingChatRequest) (string, error) {

	//0.防止错误参数
	if param.ConversationId == "" {
		param.ConversationId = "0001"
	}

	//1.创建chatModel服务
	chatModel := ai.NewChatModel(svc.ctx)
	redisChatMemory := ai.NewRedisChatMemory(svc.ctx)

	//2.添加用户对话上下文
	err := redisChatMemory.AddSingleMessage(param.ConversationId, &ai.Message{
		Role:    param.Role,
		Content: param.Prompt,
		Time:    time.Now(),
	})

	if err != nil {
		return "", err
	}

	//3.获取本次对话上下文
	chatContext, err := redisChatMemory.Get(param.ConversationId, Chat_Context_Length)
	if err != nil {
		return "", err
	}
	in := make([]*schema.Message, len(chatContext))

	for i, item := range chatContext {
		in[i] = &schema.Message{
			Role:    schema.RoleType(item.Role),
			Content: item.Content,
		}
	}

	//4.与Ai对话
	message := chatModel.BlockingChat(in)

	//5.添加系统对话上下文
	err = redisChatMemory.AddSingleMessage(param.ConversationId, &ai.Message{
		Role:    string(message.Role),
		Content: message.Content,
		Time:    time.Now(),
	})
	if err != nil {
		return "", err
	}

	return message.Content, nil
}

func (svc *Service) StreamingChat(param *StreamingChatRequest) (*schema.StreamReader[*schema.Message], error) {

	//0.防止错误参数
	if param.ConversationId == "" {
		param.ConversationId = "0001"
	}

	//1.创建chatModel服务
	chatModel := ai.NewChatModel(svc.ctx)
	redisChatMemory := ai.NewRedisChatMemory(svc.ctx)

	//2.添加用户对话上下文
	err := redisChatMemory.AddSingleMessage(param.ConversationId, &ai.Message{
		Role:    param.Role,
		Content: param.Prompt,
		Time:    time.Now(),
	})

	if err != nil {
		return nil, err
	}

	//3.获取本次对话上下文
	chatContext, err := redisChatMemory.Get(param.ConversationId, Chat_Context_Length)
	if err != nil {
		return nil, err
	}
	in := make([]*schema.Message, len(chatContext))

	for i, item := range chatContext {
		in[i] = &schema.Message{
			Role:    schema.RoleType(item.Role),
			Content: item.Content,
		}
	}

	//4.与Ai对话
	message := chatModel.StreamingChat(in)

	return message, nil
}
